import React from 'react';
import { connect } from 'react-redux';
import { ListView } from 'ywen-mobile-ui';
import BaseComponent from '../../components/common/baseComponent.js';
import CouponCell from '../../components/coupon/couponCell';
import CouponRuleModal from '../../components/coupon/couponRuleModal';

@connect(({ coupon, user }) => {
  return {
    page: coupon.getIn(['couponList', 'useable', 'page']),
    hasMore: coupon.getIn(['couponList', 'useable', 'hasMore']),
    list: coupon.getIn(['couponList', 'useable', 'list']),
    user: user.get('user'),
  };
})
class CouponList extends BaseComponent {
  componentDidMount() {
    const { user } = this.props;
    if (user.get('token')) {
      this.requestData(1);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.user !== this.props.user && nextProps.user.get('token')) {
      this.requestData(1);
    }
  }

  requestData = (targetPage) => {
    const { page } = this.props;
    this.props.dispatch({
      type: 'coupon/fetchCouponList',
      payload: {
        source: window.source,
        targetPage: targetPage || (page + 1),
        pageSize: 10,
        status: 0,
      },
    });
  }

  showRule = (coupon) => {
    this.modal.show(coupon.get('oilCompanyName').join('、'), coupon.get('content'));
  }
  render() {
    const { hasMore, list, history, dispatch } = this.props;
    const cells = list.map((coupon, index) => {
      return (
        <div className="coupon-wrapper" key={index}>
          <CouponCell coupon={coupon} type="tmall" history={history} dispatch={dispatch} clickFunc={this.showRule} />
          <div className="circle-view">
            <div className="circle left" />
            <div className="circle right" />
          </div>
          <div className="coupon-footer">
            <div className="text-row">
              <i className="iconfont icon-question" />
              <p className="text">{coupon.get('oilCompanyName').join(',')}可用。</p>
            </div>
          </div>
        </div>
      );
    });
    return (
      <div className="coupon-list">
        <ListView
          className="list"
          loadMore={this.requestData}
          hasMore={hasMore}
          empty={this.renderEmpty()}
          renderFooter={this.renderFooter}
        >
          {cells}
        </ListView>
        <CouponRuleModal ref={modal => this.modal = modal} />
      </div>
    );
  }
}

export default CouponList;
